﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.LayerManager;
using FDEEPublicFunc;

namespace FDEEInterface
{
    public class DimStyleTool
    {

        /// <summary>
        /// 判断样式是否存在
        /// </summary>
        /// <param name="DimStyleName"></param>
        /// <returns></returns>
        public static bool CheckDimStyleExists(double thescale)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            string DimStyleName = "";
            if (thescale >= 1)
                DimStyleName = "1-" + thescale.ToString();
            else
                DimStyleName = 1.0 / thescale + "-1";
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                DimStyleTableRecord dstr = new DimStyleTableRecord();
                DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForRead, true);
                if (dst.Has(DimStyleName))
                    return true;

                return false;
            }
        }

        /// <summary>
        /// 标注样式
        /// </summary>
        /// <param name="DimStyleName"></param>
        /// <param name="message"></param>
        public static void CreateModifyDimStyle(double thescale = 1.0)
        {
        
            try
            {
                using (Transaction tr = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    Database db = Application.DocumentManager.MdiActiveDocument.Database;
                    DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForWrite, true);
                    TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                    DimStyleTableRecord dstr = null;
                    string DimStyleName = "";
                    if (thescale >= 1)
                        DimStyleName = "1-" + thescale.ToString();
                    else
                        DimStyleName = 1.0 / thescale + "-1";
                    if (dst.Has(DimStyleName))
                    {
                        dstr = (DimStyleTableRecord)tr.GetObject(dst[DimStyleName], OpenMode.ForWrite);
                    }
                    else
                        dstr = new DimStyleTableRecord();

                    //dstr.Name = DimStyleName;
                    dstr.Name = DimStyleName;
                    dstr.Dimscale = thescale;
                    dstr.Dimtxsty = st[Extensions.curFont];
                    dstr.Dimclrd = Color.FromColorIndex(ColorMethod.ByAci, 3);
                    dstr.Dimclre = Color.FromColorIndex(ColorMethod.ByAci, 3);
                    dstr.Dimdli = 0;
                    dstr.Dimsah = true;

                    if (thescale == 1)
                    {
                        dstr.Dimdle = 0;
                        dstr.Dimexe = 0.075 * thescale;
                        dstr.Dimexo = 0.075 * thescale;
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen = 0.15 * thescale;
                        dstr.Dimtxt = 0.12 * thescale;
                        dstr.Dimasz = 0.1 * thescale;
                        dstr.Dimtix = true;
                        dstr.Dimtmove = 1;
                        dstr.Dimtad = 1;
                        //dstr.Dimjust = 1;
                        dstr.Dimgap = 0.05 * thescale;
                    }
                    else
                    {
                        dstr.Dimdle = 0;
                        dstr.Dimexe = 0.075 * (1.0 / thescale);
                        dstr.Dimexo = 0.075 * (1.0 / thescale);
                        dstr.DimfxlenOn = true;
                        dstr.Dimfxlen = 0.15 * (1.0 / thescale);
                        dstr.Dimtxt = 0.12 * (1.0 / thescale);
                        dstr.Dimasz = 0.1 * (1.0 / thescale);
                        dstr.Dimtix = true;
                        dstr.Dimtmove = 1;
                        dstr.Dimtad = 1;
                        //dstr.Dimjust = 1;
                        dstr.Dimgap = 0.05 * thescale * 0.15;
                    }
                    dstr.Dimdec = 3;
                    dstr.Dimtih = false;
                    dstr.Dimtoh = false;
                    dstr.Dimdsep = '.';

                    dstr.Dimlfac = 1;
                    dst.Add(dstr);
                    tr.AddNewlyCreatedDBObject(dstr, true);

                    // If the dimension style doesn't exist
                    if (!dst.Has(DimStyleName))
                    {
                        Object dsId = dst.Add(dstr);
                        tr.AddNewlyCreatedDBObject(dstr, true);
                    }
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                //message = e.Message.ToString();
            }
        }
         /// <summary>
         /// 设置当前标注样式
         /// </summary>
         /// <param name="DimStyleName"></param>
        public static void SetDimStyleCurrent(double thescale)
        {
            // Establish connections to the document and its database
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            // Establish a transaction
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                DimStyleTable dst = (DimStyleTable)tr.GetObject(db.DimStyleTableId, OpenMode.ForRead);
                ObjectId dimId = ObjectId.Null;
                string DimStyleName = "";
                if (thescale >= 1)
                    DimStyleName = "1-" + thescale.ToString();
                else
                    DimStyleName = 1.0 / thescale + "-1";
                if (!dst.Has(DimStyleName))
                {
                    CreateModifyDimStyle(thescale);
                    dimId = dst[DimStyleName];
                }
                else
                    dimId = dst[DimStyleName];

                DimStyleTableRecord dstr = (DimStyleTableRecord)tr.GetObject(dimId, OpenMode.ForRead);

                /* NOTE:
                 * If this code is used, and the updated style is current,
                 * an override is created for that style.
                 * This is not what I wanted.
                 */
                //if (dstr.ObjectId != db.Dimstyle)
                //{
                //    db.Dimstyle = dstr.ObjectId;
                //    db.SetDimstyleData(dstr);
                //}

                /* Simply by running these two lines all the time, any overrides to updated dimstyles get 
                 * cleared away as happens when you select the parent dimstyle in AutoCAD.
                 */
                db.Dimstyle = dstr.ObjectId;
                db.SetDimstyleData(dstr);

                tr.Commit();
            }
        }
        /// <summary>
        /// 获取样式id
        /// </summary>
        /// <param name="LineStyleName"></param>
        /// <returns></returns>
        public static ObjectId GetLinestyleID(string LineStyleName)
        {
            ObjectId result = ObjectId.Null;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead);
                result = ltt[LineStyleName];
                tr.Commit();
            }

            return result;
        }
        public static bool CheckTextStyle(string TextStyleName)
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acDb = acDoc.Database;

            // Ensure that the MR_ROMANS text style exists
            using (Transaction AcTrans = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
            {
                TextStyleTableRecord tstr = new TextStyleTableRecord();
                TextStyleTable tst = (TextStyleTable)AcTrans.GetObject(acDb.TextStyleTableId, OpenMode.ForRead, true, true);

                if (tst.Has(TextStyleName) == true)
                    //if (tst.Has(tst[TextStyleName]) == true)
                    return true;
                return false;
            }
        }
        public static void CreateTextStyle(string TextStyleName, string FontName, double ObliqueAng, out string message)
        {
            try
            {
                using (Transaction transaction = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())
                {
                    Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
                    TextStyleTable tst1 = (TextStyleTable)transaction.GetObject(db.TextStyleTableId, OpenMode.ForWrite, true, true);
                    TextStyleTableRecord tstr1 = new TextStyleTableRecord();
                    tstr1.Name = TextStyleName;
                    tstr1.FileName = FontName;
                    tstr1.XScale = 0.8;
                    tstr1.ObliquingAngle = GeTools.DegreeToRadian(ObliqueAng);
                    tstr1.Annotative = AnnotativeStates.True;
                    tst1.Add(tstr1);
                    transaction.TransactionManager.AddNewlyCreatedDBObject(tstr1, true);
                    transaction.Commit();
                    //RmTSid = tstr1.ObjectId;
                    //return true;
                    message = string.Empty;
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                message = e.Message.ToString();
            }
        }

        public static void CreateTextStyleByFont(Database db, string TextStyleName, string FontName, double ObliqueAng)
        {
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForWrite) as TextStyleTable;
                    if (!st.Has(TextStyleName))//字体设置
                    {
                        TextStyleTableRecord str = new TextStyleTableRecord()
                        {
                            Name = TextStyleName,
                            Font = new Autodesk.AutoCAD.GraphicsInterface.FontDescriptor(FontName, false, false, 0, 0),
                            XScale = 0.7,
                        };
                        st.Add(str);
                        tr.AddNewlyCreatedDBObject(str, true);
                    }
                    else
                    {
                        TextStyleTableRecord str = tr.GetObject(st[TextStyleName], OpenMode.ForWrite) as TextStyleTableRecord;
                        str.Font = new Autodesk.AutoCAD.GraphicsInterface.FontDescriptor(FontName, false, false, 0, 0);
                        str.XScale = 0.7;
                    }
                    tr.Commit();
       
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                
            }
        }
        public static bool CheckLinestyleExists(string LineStyleName)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                //LinetypeTableRecord lttr = new LinetypeTableRecord();
                LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead, true);
                if (ltt.Has(LineStyleName))
                    return true;

                return false;
            }
        }
        public static void LoadLinetypes(string LinFile, string LinType)
        {
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                // Open the Linetype table for read
                LinetypeTable acLineTypTbl;
                acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
                    OpenMode.ForRead) as LinetypeTable;

                if (acLineTypTbl.Has(LinType) == false)
                {
                    // Load the requested Linetype
                    acCurDb.LoadLineTypeFile(LinType, LinFile);
                }

                // Save the changes and dispose of the transaction
                acTrans.Commit();
            }
        }
       public static ObjectId GetArrowObjectId(string newArrowName)
        {
            ObjectId result = ObjectId.Null;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            string oldArrowName = Application.GetSystemVariable("DIMBLK").ToString();
            Application.SetSystemVariable("DIMBLK", newArrowName);
            if (oldArrowName.Length != 0)
                Application.SetSystemVariable("DIMBLK", oldArrowName);

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                result = bt[newArrowName];
                tr.Commit();
            }

            return result;
        }
    }
}
